package future;

import java.util.concurrent.*;

/**
 * @author fei
 * @date 2023/1/3 20:09
 * @description future中get堵塞
 */
public class FutureAPIDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        FutureTask<String> futureTask = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + "\t ------comt in");
            // 暂停几秒钟线程
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task over";
        });

        Thread thread = new Thread(futureTask, "t1");
        thread.start();

        // get 容易导致阻塞，一般建议放在程序后面，一旦调用不见不散，非要等到结果才会离开，不管你是否计算完成，容易程序堵塞
        System.out.println(futureTask.get());
        // 假如我不愿意等待很长时间，我希望过时不候，可以自动离开
        // System.out.println(futureTask.get(3, TimeUnit.SECONDS));

        System.out.println(Thread.currentThread().getName() + "\t ----忙其它任务了");
    }

}
